<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\service\DmjUserService;
use app\api\service\OilStoreService;
use app\BaseController;
use app\middleware\ApiUserAuth;
use app\model\OilAuth;
use app\Request;
use think\facade\Session;
use think\middleware\SessionInit;

/**
 * @apiDefine oilUser 用户模块
 */
class User extends BaseController
{
    protected $middleware = [
        SessionInit::class,
        ApiUserAuth::class.':continue',
    ];

    /**
     * @api  {POST} /api/user/oilLogin  用户登录
     * @apiName oilLogin 用户登录
     * @apiGroup oilUser
     * @apiDescription  根据手机号和验证码登录
     * @apiParam {String} mobile  手机号
     * @apiParam {String} verfy_code  验证码
     * @apiParam {String} cnid  页面上的cnid参数
     * @apiSuccessExample {json} 成功返回
     * {
     * 	"code": 200,
     * 	"message": "",
     * 	"data": {"token":"565658ajfadfasfa"}
     * }
     * @apiUse  AuthHeader
     * @apiUse  BaseReturn
     * @apiVersion 1.0.0
     */
    public function oilLogin(Request $request)
    {
        $rules = [
            'mobile' => 'require',
            'verfy_code' => 'require', //验证码
        ];

        $messages = ['require' => '缺少必要参数'];
        $param = $request->only(['mobile', 'cnid', 'verfy_code']);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        if (!in_array($param['mobile'], ['18922396855', '15980755471'])) { // 白名单不需要验证码校验
            if (cache('login_'.$param['mobile']) != $param['verfy_code']) {
                return fail('验证码错误');
            }
        }

        // 解密参数
        $decryptInfo = invoke(OilStoreService::class)->decryptH5Token($request->header('cipher'), $request->header('apiVersion', '1.0.0'), $param['cnid']);
        if ($decryptInfo['code']) {
            return fail($decryptInfo['msg']);
        }
        $decryptInfo = $decryptInfo['data'];
        // 登录 或者注册
        $token = Session::getId();
        $login = invoke(DmjUserService::class)->oilUserLogin($param['mobile'], $decryptInfo['cnid'], $decryptInfo['platform'], $token);
        if ($login['code']) {
            return fail($login['msg']);
        }

        return success('登录成功', ['token' => $token]);
    }

    /*
     通过authode 登录
    */
    public function oilAuthLogin(Request $request)
    {
        $param = $request->only(['auth_code' => '']);
        if (!$param['auth_code']) {
            return fail('无效认证');
        }

        $dmjUserService = invoke(DmjUserService::class);
        $user = $dmjUserService->byCode($request->param('auth_code'));
        if ($user['code']) {
            return fail($user['msg']);
        }

        $token = Session::getId();
        $login = $dmjUserService->oilUserCache($token, $user['data']);

        return success('登录成功', ['token' => $token]);
    }

    /**
     * @api  {POST} /api/user/oilAppLogin  app用户获取授权码
     * @apiName oilAppLogin
     * @apiGroup oilUser
     * @apiDescription 首页列表加油站信息获取，分页拉取时候最后一次如果拉取到的数据是空表示最后一页
     * @apiParam {String} mobile  手机号
     * @apiParam {String} cnid  页面上的cnid参数
     * @apiSuccessExample {json} 成功返回
     * {
     * 	"code": 200,
     * 	"message": "",
     * 	"data": {"auth_code":"565658ajfadfasfa"}
     * }
     * @apiUse  AuthHeader
     * @apiUse  BaseReturn
     * @apiVersion 1.0.0
     */
    public function oilAppLogin(Request $request)
    {
        $rules = [
            'mobile' => 'require',
            'cnid' => 'require',
            //'cipher' => 'require',
        ];

        $messages = ['require' => '缺少必要参数'];
        $param = $request->only(['mobile', 'cnid']);
        $param['apiVersion'] = $request->header('apiVersion');
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        $user = invoke(DmjUserService::class)->byMobile($param['mobile'], $param['cnid'], AGENT_USER_PLATFORM);
        if ($user['code']) {
            return fail($user['msg']);
        } else {
            $authData = [
                'code' => md5($user['data']['platform']['id'].'_'.REQUEST_ID),
                'app_id' => $param['cnid'],
                'related_id' => $user['data']['platform']['id'],
                'expired_at' => date('Y-m-d H:i:s', time() + 600),  // 有效期10分钟
                'try_times' => 1,  // 有效期使用次数 结合有效期
                'created_at' => date('Y-m-d H:i:s'),  // 有效期使用次数 结合有效期
            ];

            if (OilAuth::insert($authData)) {
                return success('', ['auth_code' => $authData['code']]);
            }

            doWarning('用户登录获取auth_code失败');

            return fail('请重试或者联系我们');
        }
    }

    public function oilLoginTest(Request $request)
    {
        $rules = [
            'mobile' => 'require',
            'cnid' => 'require',
        ];

        $messages = ['require' => '缺少必要参数'];
        $param = $request->only(['mobile', 'cnid']);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        // 登录 或者注册
        $token = Session::getId();
        $login = invoke(DmjUserService::class)->oilUserLogin($param['mobile'], $param['cnid'], AGENT_USER_PLATFORM, $token);
        if ($login['code']) {
            return fail($login['msg']);
        }

        return success('登录成功', ['token' => $token]);
    }

    public function loginOut()
    {
        session(null);
        if (session('?dmjuser')) {
            return fail('操作失败，请重试或者联系我们');
        }

        return success('退出成功');
    }

    /**
     * @api  {GET} /api/user/getH5  获取H5【无需做接口对接】
     * @apiName getH5
     * @apiGroup oilUser
     * @apiDescription  目前仅开放给前端获取url参数
     * @apiParam {String} cnid  页面上的cnid参数 代理商id
     * @apiSuccessExample {json} 成功返回
     * {
     * 	"code": 200,
     * 	"message": "",
     * 	"data": {}
     * }
     * @apiUse  AuthHeader
     * @apiUse  BaseReturn
     * @apiVersion 1.0.0
     */
    public function getH5(Request $request)
    {
        if (!$request->has('cnid')) {
            return  fail('cnid 参数');
        }

        return serviceResponse(invoke(OilStoreService::class)->makeH5Url($request->param('cnid'), AGENT_USER_PLATFORM));
    }
}
